﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Globalization;


namespace NDependActivities
{


    public class NDependReportReader
    {
        private XDocument _doc;

        public NDependReportReader(string reportPath)
        {
            _doc = XDocument.Load(reportPath);
        }

        public NDependReportContainer GetReportInfo()
        {
            var report = new NDependReportContainer();
            report.ReportInfo = new NDependReportInfo();

            var metricsNode = _doc.Descendants("ApplicationMetrics").First();
            var ruleResultsNode = _doc.Descendants("CQLRuleResult").First();
            var criticalRulesNodes = _doc.Descendants("RuleCritical");

            return new NDependReportContainer
            {
                ReportInfo = new NDependReportInfo
                {
                    NbSourceFiles = Convert.ToInt32(metricsNode.Attribute("NbSourceFiles").Value),
                    NbLinesOfCode = Convert.ToInt32(metricsNode.Attribute("NbLinesOfCode").Value),
                    PercentPublicType = Convert.ToDecimal(metricsNode.Attribute("PercentPublicType").Value, CultureInfo.InvariantCulture),
                    PercentPublicMethod = Convert.ToDecimal(metricsNode.Attribute("PercentPublicMethod").Value, CultureInfo.InvariantCulture),
                    NbLinesOfComment = Convert.ToInt32(metricsNode.Attribute("NbLinesOfComment").Value),
                    NClass = Convert.ToInt32(metricsNode.Attribute("NClass").Value),
                    NILInstruction = Convert.ToInt64(metricsNode.Attribute("NILInstruction").Value),
                    NNamespaces = Convert.ToInt32(metricsNode.Attribute("NNamespaces").Value),
                    NType = Convert.ToInt32(metricsNode.Attribute("NType").Value),
                    PercentageComment = Convert.ToDecimal(metricsNode.Attribute("PercentageComment").Value, CultureInfo.InvariantCulture),
                    PercentCodeCoverage = Convert.ToDecimal(metricsNode.Attribute("PercentCodeCoverage").Value, CultureInfo.InvariantCulture),
                    NbCqlQueries = Convert.ToInt32(ruleResultsNode.Attribute("NbQueries").Value, CultureInfo.InvariantCulture),
                    NbCqlQueriesErrors = Convert.ToInt32(ruleResultsNode.Attribute("NbErrors").Value, CultureInfo.InvariantCulture),
                    NbCqlQueriesWarnings = Convert.ToInt32(ruleResultsNode.Attribute("NbWarns").Value, CultureInfo.InvariantCulture),
                    NbCriticalRules = criticalRulesNodes.Count()
                },
                CriticalRules = new List<NDependCriticalRuleInfo>(criticalRulesNodes.Select(x => new NDependCriticalRuleInfo {  Name = x.Attribute("FullName").Value }))
            };
        }
    }
}
